﻿Param(
    [string] $configFile
)

if ([string]::IsNullOrWhiteSpace($configFile))
{
    $configFile = ".\Import-Data.ps1.config"
}

. .\Functions.ps1
[Reflection.Assembly]::LoadFrom(".\lib\MongoDB.Bson.dll") | Out-Null
[Reflection.Assembly]::LoadFrom(".\lib\MongoDB.Driver.dll") | Out-Null

[xml] $conf = Get-Content $configFile -Encoding UTF8

Show-Info "File path : $($conf.Config.FilePath)"
Show-Info "Connection String : $($conf.Config.ConnectionString)"

[MongoDB.Driver.MongoClient] $dbClient = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList $conf.Config.ConnectionString
[MongoDB.Driver.MongoServer] $server = $dbClient.GetServer()
[MongoDB.Driver.MongoDatabase] $database = $server.GetDatabase($conf.Config.Const.DBName)
[MongoDB.Driver.MongoCollection] $collection = $database.GetCollection($conf.Config.Const.CollectionName)

[System.Collections.Generic.List[MongoDB.Bson.BsonDocument]] $batch = New-Object "System.Collections.Generic.List[MongoDB.Bson.BsonDocument]"

Import-Csv $conf.Config.FilePath -Encoding Default | ForEach-Object {
    [MongoDB.Bson.BsonDocument] $doc = New-Object MongoDB.Bson.BsonDocument
    [MongoDB.Bson.BsonValue] $value = [MongoDB.Bson.BsonValue]::Create($_.Code)

    $doc.Add("_id", $value) | Out-Null

    $batch.Add($doc)
}

Show-Info "Remove All"
[MongoDB.Driver.WriteConcernResult] $removeAll = $collection.RemoveAll()

if ($removeAll.HasLastErrorMessage)
{
    Show-Error $removeAll.LastErrorMessage
}
else 
{
    Show-Info "Element removed : $($removeAll.DocumentsAffected)"

    Show-Info "Insert Batch"
    [MongoDB.Driver.WriteConcernResult[]] $insertBatch = $collection.InsertBatch($batch)

    [int] $countWithoutError = $insertBatch.Length
    Show-Info "Total Write concern result : $countWithoutError"

    $insertBatch | Where-Object { $_.HasLastErrorMessage } | ForEach-Object {
        Show-Error $_.LastErrorMessage
        $countWithoutError = $countWithoutError - 1
    }

    if ($countWithoutError -ne $insertBatch.Length)
    {
        Show-Error "Errors occured : $($insertBatch - $countWithoutError)"
    }
    else
    {
        Show-Info "Elements added : $countWithoutError"
    }
}
